package oj;

import java.util.ArrayDeque;
import java.util.Deque;

public class LC42 {
    public int trap(int[] height) {
        Deque<Integer> d=new ArrayDeque<>();
        int ans=0;
        for(int i=0;i<height.length;i++){
            while(!d.isEmpty() && height[d.peek()]<height[i]){
                int top=d.pop();
                if(d.isEmpty()){
                    break;
                }
                int left=d.peek();
                int wei=i-left-1;
                int hei=Math.min(height[left],height[i])-height[top];
                ans+=(wei*hei);
            }
            d.push(i);
        }
        return ans;
    }
}
